package de.ifi.lmu.snitzelhunt.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import android.util.Log;

/**
 * Helper class for HTTP Posts to the Snitzelhunt Server
 * 
 * @author jaschkowitz
 * 
 */
public class ConnectionHelper {
	/**
	 * necessary setup for the HTTP Post
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws ProtocolException
	 */
	public static HttpURLConnection setupHttpConnection(URL url)
			throws IOException, ProtocolException {
		HttpURLConnection conn;
		conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(10000);
		conn.setConnectTimeout(15000);
		conn.setRequestMethod("POST");
		conn.setDoInput(true);
		conn.setDoOutput(true);

		// HTTP Header
		conn.setRequestProperty("Content-Type", "application/json");
		return conn;
	}

	/**
	 * add a String to the HTTP Post
	 * 
	 * @param connOS
	 * @param json
	 * @throws IOException
	 */
	public static void writeString(OutputStream connOS, String json)
			throws IOException {
		BufferedWriter outW = new BufferedWriter(new OutputStreamWriter(connOS));

		outW.write(json);

		outW.flush();
		outW.close();
	}

	/**
	 * cleanup used Elements for connection
	 * 
	 * @param connIS
	 * @param connOS
	 * @param conn
	 */
	public static void cleanConnection(InputStream connIS, OutputStream connOS,
			HttpURLConnection conn) {
		if (conn != null)
			conn.disconnect();
		if (connIS != null)
			try {
				connIS.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		if (connOS != null)
			try {
				connOS.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	/**
	 * Read the server response to a String
	 * 
	 * @param connIS
	 * @return
	 * @throws IOException
	 */
	public static String readResponse(InputStream connIS) throws IOException {
		BufferedReader readURL = new BufferedReader(new InputStreamReader(
				connIS));
		StringBuilder responseB = new StringBuilder();
		String line;
		while ((line = readURL.readLine()) != null) {
			responseB.append(line);
		}
		String recv = responseB.toString();
		return recv;
	}

	/**
	 * Handle IO Exceptions in the Connection
	 * 
	 * @param e
	 */
	public static void handleIOException(IOException e) {
		e.printStackTrace();
		Log.i("snitzelhunt util", "Server down");
	}
}
